#include"my_stdio.h"


mFILE* mfopen(const char* filename, const char* mode)
{
    int fd = 0;
    if(strcmp(mode, "r") == 0)  // 只读
        fd = open(filename, O_RDONLY);
    else if(strcmp(mode, "w") == 0)  // 只写
        fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666);
    else if(strcmp(mode, "a") == 0)  // 追加   
        fd = open(filename, O_CREAT | O_WRONLY | O_APPEND, 0666);
    if(fd < 0) return NULL;
    mFILE* mf = (mFILE*)malloc(sizeof(mFILE));
    if(!mf)
    {
        close(fd);
        return NULL;
    }
    mf->capacity = SIZE;
    mf->fileno = fd;
    mf->flag = FLUSH_LINE;
    mf->size = 0;

    return mf;
}

void mfflush(mFILE* stream)
{
    if(stream->size > 0)
    {
        // 从文件内核级缓冲区刷新到外设
        write(stream->fileno, stream->out_buffer, stream->size);
        stream->size = 0;
    }
}

int mfwrite(const void* ptr, int num, mFILE* stream)
{
    // 1.拷贝
    memcpy(stream->out_buffer+stream->size, ptr, num);
    stream->size += num;

    // 2.刷新
    if(stream->flag == FLUSH_LINE && stream->size != 0 &&  stream->out_buffer[stream->size-1] == '\n')
        mfflush(stream);

}

void mfclose(mFILE* stream)
{
    // 关闭之前要刷新
    if(stream->size > 0)
        mfflush(stream);
    close(stream->fileno);
}
